package com.bjpowernode.seckillweb.service.impl;

import com.bjpowernode.constant.Constants;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

@Component
public class LuaService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    private DefaultRedisScript<Long> redisScript;

    @PostConstruct
    public void init() {
        redisScript = new DefaultRedisScript<>();
        redisScript.setResultType(Long.class);
        redisScript.setScriptSource(
                new ResourceScriptSource(
                        new ClassPathResource("seckill.lua")));
    }

    public Long runLua(Integer goodsId, Integer userId) {
        String limitKey = System.currentTimeMillis() / 1000 + "";
        String holdKey = Constants.REDIS_HOLD + goodsId + ":" + userId;
        String storeKey = Constants.REDIS_STORE + goodsId;
        List<String> keyList = Arrays.asList(limitKey, holdKey, storeKey);
        return stringRedisTemplate.execute(redisScript, keyList, String.valueOf(userId), String.valueOf(Constants.MAX_LIMIT));
    }
}